import sqlite3
import time

def main(self, sender, channel, flags, message, DB, DEBUG):

    #see if user has been in a channel with seen_nick()
    #sends last message & timestamp if seen_nick is true, via send_seen_message(), otherwise returns send_unseen_message() to channel

    def seen_nick(nick,channel):

        con=sqlite3.connect(DB)
        cur=con.cursor()
        cur.execute('SELECT nickname, message, time, channel FROM messages WHERE nickname= ? AND channel = ? ORDER BY time DESC', (nick.strip(),str(channel)))

        retval = ()

        try:
            row = cur.fetchone()
            retval = (time.ctime(row[2]), row[1])
            cur.close()
        except TypeError:
            cur.close()
            pass
        return retval

    #actually replies with message
    def send_seen_message(seen):
        time_seen = seen[0]
        seen_message = seen[1]
        self.send_channel_message(channel, "I last saw %s on %s " %(nick, time_seen))
        self.send_channel_message(channel, "%s: %s" % (nick, seen_message))

    def send_unseen_message():
        self.send_channel_message(channel, "I haven't seen %s" % (nick,))

    nick = ''
    seen = ''

    if message.startswith('seen '):
        message = message.strip('?')
        nick = message.split(' ')[1].strip()
        seen = seen_nick(nick,channel)
        if seen:
            send_seen_message(seen)
        else:
            send_unseen_message()

    if message.startswith('earlbot' + ": seen "):
        message = message.strip("?")
        nick = message.split(' ')[2].strip()
        seen = seen_nick(nick)
        if seen is not None:
            send_seen_message(seen)
        else:
            send_unseen_message()
